import { action, computed, makeObservable, observable } from 'mobx'
import Apple from './Apple'

export default class AppleStore {
  constructor () {
    this.appleList = []
    this.picking = false
    makeObservable(this, {
      appleList: observable,
      picking: observable,
      pickApple: action.bound,
      remainAppleList: computed,
      remainAppleCount: computed,
      remainAppleWeight: computed,
      eatenAppleList: computed,
      eatenAppleCount: computed,
      eatenAppleWeight: computed
    })
  }
  // 摘苹果
  pickApple () {
    this.picking = true
    setTimeout(() => {
      this.appleList.push(new Apple({
        appleId: this.generateAppleId(),
        weight: this.generateWeight()
      }))
      this.picking = false
    }, 500)
  }
  /*
   当前苹果
   */
  get remainAppleList () {
    return this.appleList.filter(apple => !apple.eaten)
  }
  get remainAppleCount () {
    return this.remainAppleList.length
  }
  get remainAppleWeight () {
    return this.remainAppleList.reduce((weight, apple) => weight += apple.weight, 0)
  }
  /*
    已吃掉苹果
   */
  get eatenAppleList () {
    return this.appleList.filter(apple => apple.eaten)
  }
  get eatenAppleCount () {
    return this.eatenAppleList.length
  }
  get eatenAppleWeight () {
    return this.eatenAppleList.reduce((weight, apple) => weight += apple.weight, 0)
  }

  generateAppleId () {
    if (!this.appleList.length) return 1
    return this.appleList.reduce((id, apple) => id < apple.appleId ? apple.appleId : id, 0) + 1
  }

  generateWeight () {
    return Math.floor(Math.random() * 51 + 200)
  }
}